package com.authentications.oauth2.auc.handler.unrealized;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName IamAccessDeniedHandler
 * @Author xiezhuocai
 * @Description TODO
 * @Date 2021/12/20 18:24
 */
public class AccessDeniedHandler extends OAuth2AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        request.setAttribute("logUpdated", "yes");
        super.handle(request, response, authException);
    }

    @Override
    protected ResponseEntity<?> enhanceResponse(ResponseEntity<?> result, Exception authException) {
        ResponseEntity<?> responseEntity = super.enhanceResponse(result, authException);
        Map<String, Object> payload = new LinkedHashMap(16);
        int code = responseEntity.getStatusCodeValue();
        String msg = authException.getMessage();
        payload.put("data", responseEntity.getBody());
        payload.put("code", code);
        if ("Access is denied".equals(msg)) {
            payload.put("msg", "没有权限访问");
        } else {
            payload.put("msg", msg);
        }

        responseEntity = new ResponseEntity(payload, responseEntity.getHeaders(), responseEntity.getStatusCode());
        return responseEntity;
    }
}
